<template>
  <view class="login-container">
   
    
    <view class="login-card">
      <view class="login-header">
        <text class="login-title">夺灵验证</text>
        
        <text class="login-hint">{{ loginHint }}</text>
      </view>
      
      <view class="login-form">
        <view class="input-group">
          <view class="input-wrapper">
            <text class="input-icon"></text>
            <input
              type="text"
              v-model="loginId"
              class="input-field"
              placeholder="请输入卡密"
              :disabled="isLoading"
            />
          </view>
        </view>
        
        <view class="time-settings">
          <view class="time-input-group">
            <view class="time-input">
              <text class="time-label">开始时间</text>
              <input
                type="time"
                v-model="timeSettings.startTime"
                class="time-picker"
                @change="handleTimeChange"
              />
            </view>
            <view class="time-input">
              <text class="time-label">结束时间</text>
              <input
                type="time"
                v-model="timeSettings.stopTime"
                class="time-picker"
                @change="handleTimeChange"
              />
            </view>
          </view>
        </view>
        
        <button 
          class="login-button" 
          :class="{ 'button-loading': isLoading }"
          @click="handleLogin"
          :disabled="isLoading"
        >
          <text v-if="!isLoading">登录</text>
          <text v-else>验证中...</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import auth from '@/utils/auth';

const loginId = ref('');
const isLoading = ref(false);
const loginHint = ref(auth.getLoginHint());
const timeSettings = ref({
  startTime: '10:00',  // 这些默认值只会在第一次使用时生效
  stopTime: '19:00'    // 之后会从存储中加载
});

// 加载保存的时间设置
const loadTimeSettings = () => {
  try {
    const savedConfig = uni.getStorageSync('plunder_config');
    if (savedConfig && savedConfig.startTime && savedConfig.stopTime) {
      // 验证时间格式
      const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
      const isValidTime = (time) => timeRegex.test(time);
      
      // 如果保存的时间格式有效，使用保存的时间
      if (isValidTime(savedConfig.startTime) && isValidTime(savedConfig.stopTime)) {
        timeSettings.value = {
          startTime: savedConfig.startTime,
          stopTime: savedConfig.stopTime
        };
        console.log('已加载保存的时间设置:', timeSettings.value);
        return;
      }
    }
    
    // 如果没有保存的配置或格式无效，使用默认值
    const defaultSettings = {
      startTime: '10:00',
      stopTime: '19:00'
    };
    
    // 保存默认设置
    const existingConfig = uni.getStorageSync('plunder_config') || {};
    const updatedConfig = {
      ...existingConfig,
      ...defaultSettings
    };
    uni.setStorageSync('plunder_config', updatedConfig);
    
    timeSettings.value = defaultSettings;
    console.log('使用默认时间设置:', defaultSettings);
  } catch (e) {
    console.error('加载时间设置失败:', e);
    // 出错时使用默认值
    timeSettings.value = {
      startTime: '10:00',
      stopTime: '19:00'
    };
  }
};

// 加载保存的卡密
const loadSavedLoginId = () => {
  const savedLoginId = uni.getStorageSync('saved_login_id');
  if (savedLoginId) {
    loginId.value = savedLoginId;
  }
};

// 修改登录处理函数
const handleLogin = async () => {
  if (!loginId.value) {
    uni.showToast({
      title: '请输入卡密',
      icon: 'none'
    });
    return;
  }

  isLoading.value = true;
  try {
    // 调用登录函数进行验证
    const result = await auth.login(loginId.value);

    if (result.success) {
      // 保存卡密到本地存储
      uni.setStorageSync('saved_login_id', loginId.value);
      
      // 获取现有的配置
      const existingConfig = uni.getStorageSync('plunder_config') || {};
      
      // 更新配置，保留现有配置和时间设置
      const updatedConfig = {
        ...existingConfig,
        startTime: timeSettings.value.startTime,
        stopTime: timeSettings.value.stopTime
      };
      
      // 保存到 plunder_config
      uni.setStorageSync('plunder_config', updatedConfig);
      console.log('登录时保存的时间设置:', updatedConfig);
      
      // 检查是否是首次登录或重新登录
      const lastLoginTime = uni.getStorageSync('last_login_time');
      const now = Date.now();
      const isFirstLogin = !lastLoginTime;
      const isReLogin = lastLoginTime && (now - lastLoginTime > 24 * 60 * 60 * 1000);
      
      if (isFirstLogin || isReLogin) {
        uni.showToast({
          title: '登录成功',
          icon: 'success'
        });
      }
      
      // 更新最后登录时间
      uni.setStorageSync('last_login_time', now);
      
      // 登录成功后跳转到首页
      setTimeout(() => {
        uni.reLaunch({
          url: '/pages/index/home'
        });
      }, 1500);
    } else {
      uni.showToast({
        title: result.message || '登录失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('登录失败:', error);
    uni.showToast({
      title: '登录失败，请稍后重试',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
};

// 修改时间设置变更处理函数
const handleTimeChange = () => {
  try {
    // 验证时间格式
    const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
    const isValidTime = (time) => timeRegex.test(time);
    
    // 验证并修正时间格式
    const startTime = isValidTime(timeSettings.value.startTime) ? timeSettings.value.startTime : timeSettings.value.startTime;
    const stopTime = isValidTime(timeSettings.value.stopTime) ? timeSettings.value.stopTime : timeSettings.value.stopTime;
    
    // 更新本地时间设置
    timeSettings.value = {
      startTime,
      stopTime
    };
    
    // 获取现有的配置
    const existingConfig = uni.getStorageSync('plunder_config') || {};
    
    // 更新配置，保留现有配置，添加时间设置
    const updatedConfig = {
      ...existingConfig,
      startTime,
      stopTime
    };
    
    // 保存到 plunder_config
    uni.setStorageSync('plunder_config', updatedConfig);
    console.log('已保存新的时间设置:', updatedConfig);
    
    // 更新全局状态
    auth.updateGlobalState('timeSettings', timeSettings.value);
    
    // 显示保存成功提示
    uni.showToast({
      title: '时间设置已保存',
      icon: 'success',
      duration: 1500
    });
  } catch (e) {
    console.error('保存时间设置失败:', e);
    uni.showToast({
      title: '保存时间设置失败',
      icon: 'none',
      duration: 1500
    });
  }
};

// 页面加载时加载时间设置和卡密
onMounted(() => {
  loadTimeSettings();        // 加载时间设置
  loadSavedLoginId();        // 加载保存的卡密
});
</script>

<style>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);
  padding: 32rpx;
  padding-top: 32rpx;
}

.login-card {
  width: 100%;
  max-width: 600rpx;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 24rpx;
  padding: 48rpx 32rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
  animation: slideUp 0.5s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-header {
  text-align: center;
  margin-bottom: 48rpx;
}

.login-title {
  font-size: 40rpx;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 16rpx;
  display: block;
}

.login-subtitle {
  font-size: 28rpx;
  color: #666;
  display: block;
}

.login-hint {
  font-size: 24rpx;
  color: #409eff;
  margin-top: 8rpx;
  display: block;
  text-align: center;
  background: rgba(64, 158, 255, 0.1);
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  display: inline-block;
  margin-top: 16rpx;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 32rpx;
}

.input-group {
  position: relative;
  margin: 24rpx 0;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  background: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.input-wrapper:focus-within {
  box-shadow: 0 4rpx 16rpx rgba(64, 158, 255, 0.15);
  transform: translateY(-2rpx);
}

.input-icon {
  padding: 0 24rpx;
  font-size: 32rpx;
  color: #909399;
}

.input-field {
  flex: 1;
  height: 96rpx;
  background: transparent;
  border: none;
  padding: 0 24rpx;
  font-size: 30rpx;
  color: #333333;
  transition: all 0.3s ease;
}

.input-field::placeholder {
  color: #c0c4cc;
  font-size: 28rpx;
}

.input-field:disabled {
  background: #f5f7fa;
  cursor: not-allowed;
}

.input-field:focus {
  outline: none;
}

.login-button {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #409eff 0%, #3a8ee6 100%);
  border-radius: 12rpx;
  color: white;
  font-size: 32rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  border: none;
}

.login-button:active {
  transform: scale(0.98);
}

.button-loading {
  opacity: 0.8;
  cursor: not-allowed;
}

@media screen and (min-width: 768px) {
  .login-card {
    padding: 64rpx 48rpx;
  }
  
  .login-title {
    font-size: 48rpx;
  }
  
  .login-subtitle {
    font-size: 32rpx;
  }
}

.time-settings {
  margin: 24rpx 0;
  padding: 20rpx;
  background: rgba(248, 249, 250, 0.8);
  border-radius: 12rpx;
  border: 1rpx solid rgba(220, 223, 230, 0.8);
}

.time-input-group {
  display: flex;
  gap: 20rpx;
}

.time-input {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.time-label {
  font-size: 24rpx;
  color: #606266;
  font-weight: 500;
}

.time-picker {
  background: rgba(255, 255, 255, 0.9);
  border: 1rpx solid rgba(220, 223, 230, 0.8);
  border-radius: 8rpx;
  padding: 12rpx;
  font-size: 24rpx;
  color: #1a1a1a;
  transition: all 0.3s ease;
}

.time-picker:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2rpx rgba(64, 158, 255, 0.2);
  outline: none;
}
</style> 